package entity

import (
	"bytes"
	"fmt"
	"gopkg.in/yaml.v3"
	"os"
	"strings"
	"ytDownload/logger"
)

var configP *PropertyStruct

func init() {
	allArgs := os.Args[1:]
	env := "prod"
outOfSetEnv:
	for _, arg := range allArgs {
		switch strings.ToLower(arg) {
		case "dev":
			env = "dev"
			logger.Infof("当前环境:%s\n", arg)
			break outOfSetEnv
		case "prod":
			env = "prod"
			logger.Infof("当前环境:%s\n", arg)
			break outOfSetEnv
		}
	}

	propertyFile := fmt.Sprintf("./property_%s.yaml", env)
	if env == "prod" {
		_, err := os.Stat(propertyFile)
		if err != nil {
			propertyFile = "./property.yaml"
			logger.Errorf("prod 配置文件不存在，更改配置文件为:%s", propertyFile)
		}
	}
	logger.Infof("读取配置文件...[%s]", propertyFile)
	// 读取配置文件
	config, err := ReadConfig(propertyFile)
	if err != nil {
		logger.Errorf("error reading config: %v", err)
		panic(err)
	}
	configP = config

	logger.Infof(fmt.Sprintf("读取配置文件结束:%v", *configP))
}

type PropertyStruct struct {
	HandmadeIndex          string `name:"Handmade视频首页" yaml:"handmadeIndex"`
	SaveDir                string `name:"EF2的下载目录" yaml:"saveDir"`
	ResourceDir            string `name:"资源目录" yaml:"resourceDir"`
	MergeOutputDir         string `name:"合并输出目录" yaml:"mergeOutputDir"`
	SubtitleSaveDir        string `name:"字幕保存目录" yaml:"subtitleSaveDir"`
	SubtitleMergeOutputDir string `name:"字幕合并输出目录" yaml:"subtitleMergeOutputDir"`
}

func GetSaveDir() string {
	return (*configP).SaveDir
}

func GetResourceDir() string {
	return (*configP).ResourceDir
}

func GetMergeOutputDir() string {
	return (*configP).MergeOutputDir
}

func GetHandmadeIndex() string {
	return (*configP).HandmadeIndex
}

func GetSubtitleSaveDir() string {
	return (*configP).SubtitleSaveDir
}

func GetSubtitleMergeOutputDir() string {
	return (*configP).SubtitleMergeOutputDir
}

func ReadConfig(configPath string) (*PropertyStruct, error) {
	fileBytes, err := os.ReadFile(configPath)
	if err != nil {
		return nil, err
	}

	reader := bytes.NewReader(fileBytes)
	decoder := yaml.NewDecoder(reader)

	var config PropertyStruct

	err = decoder.Decode(&config)
	if err != nil {
		return nil, err
	}

	return &config, nil
}
